package com.dmw.controller;

import com.dmw.dto.Dto;
import com.dmw.entity.DmLinkUser;
import com.dmw.entity.DmUser;
import com.dmw.service.DmUserService;
import com.dmw.util.DtoUtil;
import com.dmw.util.MD5;
import com.dmw.util.RedisUtil;
import com.dmw.util.TokenUtil;
import com.dmw.vo.TokenVO;
import com.dmw.vo.placeOrderVO.TicketBuyerListOfUserIdVO;
import com.dmw.vo.userBuyTicketsVO.AddBuyTicketsVo;
import com.dmw.vo.userInfoPageVO.ModifyUserInfoVo;
import com.dmw.vo.userInfoPageVO.ReturnUserInfoTokenVO;
import com.dmw.vo.userLoginVO.LoginVO;
import com.dmw.vo.userLoginVO.PasswordLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Configuration
public class UserProviderController {

    @Autowired
    private DmUserService userService;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private HttpServletRequest requestNow;
    @Autowired
    private RedisUtil redisUtil;

    //激活码前缀
    private String active_prefix = "active:";


    /**
     * 根据用户token返回用户信息
     * from 个人信息页面接口 1
     * @return
     */
    @RequestMapping("/queryUserInfoByToken")
    public Dto queryUserInfoByToken(@RequestBody Map<String, Object> map){
        System.out.println(">>>come");

        //token 失效处理
        String token = map.get("token").toString();
        System.out.println(token);
        String tokenKey="token:"+token;
        if (token == null||!redisUtil.hasKey(tokenKey)) {
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }

        String[] s = token.split("-");
        Long userId=Long.valueOf(s[2]);

        List<ReturnUserInfoTokenVO> list = null;
        try {
            list = userService.queryUserInfoByToken(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnDataSuccess(list.get(0));
    }

    /**
     * 修改用户信息
     * from 个人信息页面接口 2
     * @return
     */
    @RequestMapping("/modifyUserInfo")
    public Dto modifyUserInfo(@RequestBody Map<String, Object> map){
        System.out.println(">>>come");
        System.out.println(map);

        //token 失效处理
        String token = map.get("token").toString();
        String tokenKey="token:"+token;
        if (token == null||!redisUtil.hasKey(tokenKey)) {
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }

        String[] s = token.split("-");
        Long userId=Long.valueOf(s[2]);
        map.put("id",userId);

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            if(map.get("birthday")!=null) {
                String birthday = map.get("birthday").toString();
                String date=birthday.substring(0,birthday.lastIndexOf(".")).replace("T"," ");
                map.put("birthday", sdf.parse(date));
            }
            System.out.println(map.get("birthday"));
            map.put("updatedTime",sdf.parse(sdf.format(new Date())));
            userService.modifyUserInfo(map);
//            PasswordLoginVO pvo=list.get(0);
        }catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnSuccess();
    }

    /**
     * 根据当前用户返回当前用户常用购票人列表
     * from 常用购票人页面 1
     * @return
     */
    @RequestMapping("/queryLinkUser")
    public Dto queryLinkUser(@RequestBody Map<String, Object> map){
        System.out.println(">>>come");

        //token 失效处理
        String token = map.get("token").toString();
        System.out.println(token);
        String tokenKey="token:"+token;
        if (token == null||!redisUtil.hasKey(tokenKey)) {
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }

        String[] s = token.split("-");
        Integer userId=Integer.valueOf(s[2]);

        List<TicketBuyerListOfUserIdVO> list = null;
        try {
            list = userService.queryLinkUser(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnDataSuccess(list);
    }

    /**
     * 添加常用购票人
     * from 常用购票人页面 2
     * @return
     */
    @RequestMapping("/addLinkUser")
    public Dto addLinkUser(@RequestBody Map<String, Object> map){
        System.out.println(">>>come");
        System.out.println(map);
        //token 失效处理
        String token = map.get("token").toString();
        String tokenKey="token:"+token;
        if (token == null||!redisUtil.hasKey(tokenKey)) {
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }

        String[] s = token.split("-");
        Long userId=Long.valueOf(s[2]);
//        System.out.println("userId:"+userId);

        DmLinkUser user=new DmLinkUser();
        user.setUserid(userId);
        user.setName(map.get("name").toString());
        user.setIdcard((String) map.get("idCard"));
        user.setCardtype(Integer.valueOf(map.get("cardType").toString()));
//        Date date=new Date();
//        System.out.println(date);
        user.setCreatedtime(new Date());

        try {
            userService.addLinkUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnSuccess();
    }

    /**
     * 验证购票人是否已经存在
     * from 常用购票人页面 3
     * @return
     */
    @RequestMapping("/queryLinkUserByIdCard")
    public Dto queryLinkUserByIdCard(@RequestBody Map<String, Object> map){
        System.out.println(">>>come");
        System.out.println(map.get("isCard"));
        //token 失效处理
        String token = map.get("token").toString();
        System.out.println(token);
        String tokenKey="token:"+token;
        if (token == null||!redisUtil.hasKey(tokenKey)) {
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }

        String[] s = token.split("-");
        Long userId=Long.valueOf(s[2]);
        map.put("userId",userId);


        int count = 0;
        try {
            count = userService.queryLinkUserByIdCard(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (count==0)
        return DtoUtil.returnSuccess();
        return DtoUtil.returnFail("购票人是否已经存在","10000");
    }

    /**
     * 删除联系人
     * from 常用购票人页面 4
     * @return
     */
    @RequestMapping("/deleteLinkUserById")
    public Dto deleteLinkUserById(@RequestBody Map<String, Object> map){
        System.out.println(">>>come");
        System.out.println(map.get("id"));
        map.put("userId",map.get("userId"));

        String token = map.get("token").toString();
        System.out.println(token);
        String tokenKey="token:"+token;
        if (token == null||!redisUtil.hasKey(tokenKey)) {
            return DtoUtil.returnFail("token失效，请重登录", "100000");
        }

        try {
            userService.deleteLinkUserById(Long.valueOf(map.get("id").toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  DtoUtil.returnSuccess();
    }

    /**
     * 用户登录 生成token
     * @return
     */
    @PostMapping("/login")
    public Dto login(@RequestBody Map<String, Object> map){
        System.out.println("用户登录~~~");
        System.out.println(map.get("phone"));
        System.out.println(map.get("password"));

        map.put("password", MD5.getMd5(map.get("password").toString(),32));
        //查询
        List<PasswordLoginVO> list = null;
        try {
            list = userService.login(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断 查询结果
        if(list.size()!=0){

            PasswordLoginVO pvo=list.get(0);
            //生成token
            String token = tokenUtil.generateToken(map.get("phone").toString(),pvo.getUserId(),requestNow.getHeader("user-agent"));

            //保存
            tokenUtil.save(token, pvo);
            String substring = token.substring(6);
            try {
                TokenVO tokenVO=new TokenVO(substring,tokenUtil.getTimeout(),tokenUtil.getLogin(token));
                List<Object> list1=new ArrayList<>();
                list1.add(pvo);
                list1.add(tokenVO);
                return DtoUtil.returnSuccess("登陆成功",list1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return DtoUtil.returnFail("账号或密码错误","1006");
    }


    /**
     * 验证手机号是否可用接口
     * @param map
     * @return
     */
    @PostMapping("checkEmail")
    public Dto checkEmail(@RequestBody Map<String, Object> map){
        System.out.println(">>>验证邮箱号是否可用接口");
        System.out.println(map.get("phone"));

        //添加用户
        try {
            int count = userService.checkEmail(map.get("phone").toString());
            if(count==1)
                return DtoUtil.returnFail("邮箱已注册","1003");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnSuccess("邮箱未被注册");
    }

    /**
     * 使用邮箱号注册接口
     * @param map
     * @return
     */
    @PostMapping("register")
    public Dto register(@RequestBody Map<String, Object> map){
        System.out.println(">>>使用邮箱号注册接口");
        System.out.println(map);
        //添加用户
        String b="";
        try {
            b = userService.register(map);
            if(b.equals("1002")) return DtoUtil.returnFail("该邮箱用户已存在！","1002");
            if(b.equals("1004")) return DtoUtil.returnFail("验证码错误！","1004");
            if(b.equals("0000"))  return DtoUtil.returnSuccess("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnFail("注册失败","1002");
    }
}
